package com.canyou.integration.authenticator;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.canyou.captcha.KaptchaConfig;
import com.canyou.enums.ErrorCodeEnum;
import com.canyou.exception.CysBusinessException;
import com.canyou.integration.IntegrationAuthentication;
import com.canyou.integration.IntegrationClientConstant;
import com.canyou.system.model.User;
import com.canyou.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * web后台登录处理
 *
 * @author fy
 * @date 2021-03-10
 **/
@Component
@Primary
public class AdminWebAuthenticator extends AbstractIntegrationAuthenticator {

    private static final String GRANT_TYPE = "password";

    @Autowired
    private UserService userService;

    @Override
    public User authenticate(IntegrationAuthentication integrationAuthentication) {
        // 判断grant_type, 只有在登录`password`情况下才需要验证码
        // 如果是refresh_token, 是不需要验证码的
        String grantType = integrationAuthentication.getAuthParameter("grant_type");

        if (GRANT_TYPE.equalsIgnoreCase(grantType)) {
            String generateKey = integrationAuthentication.getAuthParameter("generate_key");
            String captchaCode = integrationAuthentication.getAuthParameter("captcha_code");
            if (StrUtil.isBlank(generateKey)) {
                throw new CysBusinessException(ErrorCodeEnum.ILLEGAL, "generate_key不能为空");
            }
            if (StrUtil.isBlank(captchaCode)) {
                throw new CysBusinessException(ErrorCodeEnum.ILLEGAL, "验证码不能为空");
            }
            String cacheCaptchaCode = KaptchaConfig.getKaptcha(generateKey);
            if (!captchaCode.equalsIgnoreCase(cacheCaptchaCode)) {
                throw new CysBusinessException(ErrorCodeEnum.ILLEGAL, "验证码不正确");
            }
        }
        String username = integrationAuthentication.getUsername();
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {
    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return IntegrationClientConstant.AUTH_TYPE_ADMIN_WEB.equalsIgnoreCase(integrationAuthentication.getAuthType());
    }
}
